<template>
  <div class="container">
    <Breadcrumb :items="['menu.project', 'menu.route.edit']" />
    <a-form ref="formRef" layout="vertical" :model="formData">
      <a-space direction="vertical" :size="16">
        <a-card class="general-card">
          <template #title>
            {{ $t('route.title.basic') }}
          </template>
          <a-row :gutter="80">
            <a-col :span="8">
              <a-form-item :label="$t('route.enabled')" field="enabled">
                <a-radio-group v-model="formData.enabled">
                  <a-radio :value="true">{{ $t('radio.enabled') }}</a-radio>
                  <a-radio :value="false">{{ $t('radio.disabled') }}</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="$t('downstream.http.version')"
                field="downstreamHttpVersion"
              >
                <a-select
                  v-model="formData.downstreamHttpVersion"
                  allow-clear
                  :placeholder="$t('route.placeholder.downstream.http.version')"
                >
                  <a-option value="1.0">1.0</a-option>
                  <a-option value="1.1">1.1</a-option>
                  <a-option value="2.0">2.0</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="$t('downstream.path.template')"
                field="downstreamPathTemplate"
              >
                <a-input
                  v-model="formData.downstreamPathTemplate"
                  :placeholder="
                    $t('route.placeholder.downstream.path.template')
                  "
                >
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="80">
            <a-col :span="8">
              <a-form-item
                :label="$t('downstream.scheme')"
                field="downstreamScheme"
              >
                <a-select
                  v-model="formData.downstreamScheme"
                  allow-clear
                  :placeholder="$t('route.placeholder.downstream.scheme')"
                >
                  <a-option value="http">http</a-option>
                  <a-option value="https">https</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="$t('upstream.path.template')"
                field="upstreamPathTemplate"
              >
                <a-input
                  v-model="formData.upstreamPathTemplate"
                  :placeholder="$t('route.placeholder.upstream.path.template')"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="$t('upstream.host')" field="upstreamHost">
                <a-input
                  v-model="formData.upstreamHost"
                  :placeholder="$t('route.placeholder.upstream.host')"
                >
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="80">
            <a-col :span="8">
              <a-form-item
                :label="$t('upstream.http.method')"
                field="upstreamHttpMethod"
              >
                <a-checkbox-group v-model="formData.upstreamHttpMethod">
                  <a-checkbox value="Get">GET</a-checkbox>
                  <a-checkbox value="Post">POST</a-checkbox>
                  <a-checkbox value="Put">PUT</a-checkbox>
                  <a-checkbox value="Delete">DELETE</a-checkbox>
                  <a-checkbox value="Patch">PATCH</a-checkbox>
                  <a-checkbox value="Option">OPTION</a-checkbox>
                </a-checkbox-group>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="$t('downstream.http.method')"
                field="downstreamHttpMethod"
              >
                <a-select
                  v-model="formData.downstreamHttpMethod"
                  allow-clear
                  :placeholder="$t('route.placeholder.downstream.http.method')"
                >
                  <a-option value="Get">GET</a-option>
                  <a-option value="Post">POST</a-option>
                  <a-option value="Put">PUT</a-option>
                  <a-option value="Delete">DELETE</a-option>
                  <a-option value="Patch">PATCH</a-option>
                  <a-option value="Option">OPTION</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="$t('route.requestIdKey')"
                field="ServicediscoveryConfigurationkey"
              >
                <a-input
                  v-model="formData.requestIdKey"
                  :placeholder="$t('route.placeholder.requestIdKey')"
                >
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="80">
            <a-col :span="8">
              <a-form-item
                :label="$t('route.delegating.handlers')"
                field="delegatingHandlers"
              >
                <!-- <a-input
                  v-model="formData.delegatingHandlers"
                  :placeholder="$t('route.delegating.handlers')"
                >
                </a-input> -->
                <a-space wrap>
                  <a-tag
                    v-for="tag of formData.delegatingHandlers"
                    :key="tag"
                    size="large"
                    :closable="true"
                    @close="handleRemoveDelegatingHandlersTag(tag)"
                  >
                    {{ tag }}
                  </a-tag>

                  <a-input
                    v-if="showDelegatingHandlersInput"
                    ref="inputDelegatingHandlersRef"
                    v-model.trim="inputDelegatingHandlersVal"
                    :style="{ width: '90px' }"
                    @keyup.enter="handleAddDelegatingHandlersTag"
                    @blur="handleAddDelegatingHandlersTag"
                  />
                  <a-tag
                    v-else
                    size="large"
                    :style="{
                      width: '90px',
                      backgroundColor: 'var(--color-fill-2)',
                      border: '1px dashed var(--color-fill-3)',
                      cursor: 'pointer',
                    }"
                    @click="handleEditDelegatingHandlersTag"
                  >
                    <template #icon>
                      <icon-plus />
                    </template>
                    {{ $t('rate.limit.add.white.list') }}
                  </a-tag>
                </a-space>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="$t('route.cacheTtlseconds')"
                field="cacheTtlseconds"
              >
                <a-input-number
                  v-model="formData.cacheTtlseconds"
                  :hide-button="true"
                  :placeholder="$t('route.cacheTtlseconds')"
                >
                  <template #append> {{ $t('unit.second') }} </template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="$t('route.cache.region')"
                field="cacheRegion"
              >
                <a-input
                  v-model="formData.cacheRegion"
                  :placeholder="$t('route.placeholder.cache.region')"
                >
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="80">
            <a-col :span="8">
              <a-form-item
                :label="$t('route.routeIsCaseSensitive')"
                field="routeIsCaseSensitive"
              >
                <a-radio-group v-model="formData.routeIsCaseSensitive">
                  <a-radio :value="true">{{ $t('radio.use') }}</a-radio>
                  <a-radio :value="false">{{ $t('radio.not.use') }}</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="
                  $t('route.dangerousAcceptAnyServerCertificateValidator')
                "
                field="dangerousAcceptAnyServerCertificateValidator"
              >
                <a-radio-group
                  v-model="
                    formData.dangerousAcceptAnyServerCertificateValidator
                  "
                >
                  <a-radio :value="true">{{ $t('radio.use') }}</a-radio>
                  <a-radio :value="false">{{ $t('radio.not.use') }}</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :label="$t('route.service.name')"
                field="serviceName"
              >
                <a-input
                  v-model="formData.serviceName"
                  :placeholder="$t('route.placeholder.service.name')"
                >
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="80">
            <a-col :span="8">
              <a-form-item
                :label="$t('route.service.namespace')"
                field="serviceNamespace"
              >
                <a-input
                  v-model="formData.serviceNamespace"
                  :placeholder="$t('route.placeholder.service.namespace')"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="$t('route.priority')" field="priority">
                <a-input-number
                  v-model="formData.priority"
                  :hide-button="true"
                  :placeholder="$t('route.priority')"
                >
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="$t('route.timeout')" field="timeout">
                <a-input-number
                  v-model="formData.timeout"
                  :hide-button="true"
                  :placeholder="$t('route.timeout')"
                >
                  <template #append> {{ $t('unit.ms') }} </template>
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="80">
            <a-col :span="8">
              <a-form-item :label="$t('route.key')" field="routekey">
                <a-input
                  v-model="formData.key"
                  :placeholder="$t('route.placeholder.route.key')"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="$t('route.sort')" field="sort">
                <a-input-number
                  v-model="formData.sort"
                  :placeholder="$t('route.placeholder.route.sort')"
                >
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card class="general-card" :bordered="false">
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" :title="$t('route.host.port')">
              <a-row style="margin-bottom: 16px">
                <a-col :span="16">
                  <a-space>
                    <a-button
                      type="primary"
                      @click="handleEdit(true, undefined)"
                    >
                      <template #icon>
                        <icon-plus />
                      </template>
                      {{ $t('routeTable.operation.create') }}
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
              <a-table
                row-key="id"
                :loading="loading"
                :data="formData.routeHostPorts"
                :bordered="false"
              >
                <template #columns>
                  <a-table-column title="Host" data-index="host" />
                  <a-table-column :title="$t('route.port')" data-index="port" />
                  <a-table-column
                    :title="$t('routeTable.columns.operations')"
                    data-index="operations"
                  >
                    <template #cell="{ record }">
                      <a-space>
                        <a-button
                          type="outline"
                          size="small"
                          @click="handleEdit(false, record)"
                        >
                          {{ $t('routeTable.columns.operations.edit') }}
                        </a-button>
                        <a-button
                          type="primary"
                          size="small"
                          status="danger"
                          @click="handleDelete(record)"
                        >
                          {{ $t('routeTable.columns.operations.del') }}
                        </a-button>
                      </a-space>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="2" :title="$t('detailForm.title.qos')">
              <a-row :gutter="80">
                <a-col :span="8">
                  <a-form-item
                    :label="$t('qos.exceptions.allowed.before.breaking')"
                  >
                    <a-input
                      v-model="formData.qosExceptionsallowedbeforebreaking"
                      placeholder="打开断路器之前允许的例外数量"
                      autocomplete="off"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="$t('qos.duration.of.break')">
                    <a-input
                      v-model="formData.qosDurationofbreak"
                      placeholder="断路器复位之前，打开的时间"
                      autocomplete="off"
                    >
                      <template #append> {{ $t('unit.ms') }} </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="$t('qos.timeout.value')">
                    <a-input
                      v-model="formData.qosTimeoutvalue"
                      placeholder="请求超时时间"
                      autocomplete="off"
                    >
                      <template #append> {{ $t('unit.ms') }} </template>
                    </a-input>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-tab-pane>
            <a-tab-pane key="3" :title="$t('detailForm.title.rate.limit')">
              <a-row :gutter="80">
                <a-col :span="6">
                  <a-form-item
                    label="是否启用流量限制"
                    field="ratelimitEnableratelimiting"
                  >
                    <a-radio-group
                      v-model="formData.ratelimitEnableratelimiting"
                    >
                      <a-radio :value="true">{{ $t('radio.enabled') }}</a-radio>
                      <a-radio :value="false">{{
                        $t('radio.disabled')
                      }}</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item :label="$t('rate.limit.period')">
                    <a-input
                      v-model="formData.ratelimitPeriod"
                      placeholder="限制期，如1s、1m、1h"
                      autocomplete="off"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="限制期时间戳">
                    <a-input
                      v-model="formData.ratelimitPeriodtimespan"
                      laceholder="限制期时间戳"
                      autocomplete="off"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label="最大请求数">
                    <a-input
                      v-model="formData.ratelimitLimit"
                      placeholder="客户端在定义的时间段内可以发出的最大请求数"
                      autocomplete="off"
                    ></a-input>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="80">
                <a-col :span="24">
                  <a-form-item label="限流白名单">
                    <a-space wrap>
                      <a-tag
                        v-for="tag of formData.ratelimitWhitelist"
                        :key="tag"
                        size="large"
                        :closable="true"
                        @close="handleRemoveWhiteListTag(tag)"
                      >
                        {{ tag }}
                      </a-tag>

                      <a-input
                        v-if="showWhiteListInput"
                        ref="inputWhiteListRef"
                        v-model.trim="inputWhiteListVal"
                        :style="{ width: '90px' }"
                        @keyup.enter="handleAddWhiteListTag"
                        @blur="handleAddWhiteListTag"
                      />
                      <a-tag
                        v-else
                        size="large"
                        :style="{
                          width: '90px',
                          backgroundColor: 'var(--color-fill-2)',
                          border: '1px dashed var(--color-fill-3)',
                          cursor: 'pointer',
                        }"
                        @click="handleEditWhiteListTag"
                      >
                        <template #icon>
                          <icon-plus />
                        </template>
                        {{ $t('rate.limit.add.white.list') }}
                      </a-tag>
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-tab-pane>
            <a-tab-pane key="4" :title="$t('authentication.manager')">
              <a-row :gutter="80">
                <a-col :span="8">
                  <a-form-item :label="$t('authentication.provider.key')">
                    <a-input
                      v-model="formData.authenticationAuthenticationproviderkey"
                      placeholder="这个key对应的是代码中.AddJWTBreark中的Key"
                      autocomplete="off"
                    ></a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="16">
                  <a-form-item :label="$t('authentication.allowed.scopes')">
                    <a-space wrap>
                      <a-tag
                        v-for="tag of formData.authenticationAllowedscopes"
                        :key="tag"
                        size="large"
                        :closable="true"
                        @close="handleRemoveScopeTag(tag)"
                      >
                        {{ tag }}
                      </a-tag>

                      <a-input
                        v-if="showScopeInput"
                        ref="inputScopeRef"
                        v-model.trim="inputScopeVal"
                        :style="{ width: '90px' }"
                        @keyup.enter="handleAddScopeTag"
                        @blur="handleAddScopeTag"
                      />
                      <a-tag
                        v-else
                        size="large"
                        :style="{
                          width: '90px',
                          backgroundColor: 'var(--color-fill-2)',
                          border: '1px dashed var(--color-fill-3)',
                          cursor: 'pointer',
                        }"
                        @click="handleEditScopeTag"
                      >
                        <template #icon>
                          <icon-plus />
                        </template>
                        {{ $t('authentication.add.scope') }}
                      </a-tag>
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-tab-pane>
            <a-tab-pane key="5" :title="$t('http.handler')">
              <a-row :gutter="80">
                <a-col :span="6">
                  <a-form-item :label="$t('http.handler.allow.auto.redirect')">
                    <a-radio-group
                      v-model="formData.httphandlerAllowautoredirect"
                    >
                      <a-radio :value="true">{{ $t('radio.allow') }}</a-radio>
                      <a-radio :value="false">{{
                        $t('radio.not.allow')
                      }}</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item :label="$t('http.handler.use.cookie.container')">
                    <a-radio-group
                      v-model="formData.httphandlerUsecookiecontainer"
                    >
                      <a-radio :value="true">{{ $t('radio.use') }}</a-radio>
                      <a-radio :value="false">{{
                        $t('radio.not.use')
                      }}</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item :label="$t('http.handler.use.tracing')">
                    <a-radio-group v-model="formData.httphandlerUsetracing">
                      <a-radio :value="true">{{ $t('radio.use') }}</a-radio>
                      <a-radio :value="false">{{
                        $t('radio.not.use')
                      }}</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item :label="$t('http.handler.use.proxy')">
                    <a-radio-group v-model="formData.httphandlerUseproxy">
                      <a-radio :value="true">{{ $t('radio.use') }}</a-radio>
                      <a-radio :value="false">{{
                        $t('radio.not.use')
                      }}</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="80">
                <a-col :span="6">
                  <a-form-item
                    :label="$t('http.handler.max.connections.per.server')"
                  >
                    <a-input-number
                      v-model="formData.httphandlerMaxconnectionsperserver"
                      :hide-button="true"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-tab-pane>
            <a-tab-pane key="6" :title="$t('load.balancer')">
              <a-row :gutter="80">
                <a-col :span="6">
                  <a-form-item
                    :label="$t('load.balancer.type')"
                    field="loadbalancerType"
                  >
                    <a-select
                      v-model="formData.loadbalancerType"
                      allow-clear
                      :placeholder="
                        $t('detailForm.placeholder.load.balancer.type')
                      "
                    >
                      <a-option value="LeastConnection">{{
                        $t('load.balancer.type.least.connection')
                      }}</a-option>
                      <a-option value="RoundRobin">{{
                        $t('load.balancer.type.round.robin')
                      }}</a-option>
                      <a-option value="NoLoadBalance">{{
                        $t('load.balancer.type.no.load.balance')
                      }}</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item
                    :label="$t('load.balancer.key')"
                    field="loadbalancerKey"
                  >
                    <a-input
                      v-model="formData.loadbalancerKey"
                      :placeholder="
                        $t('detailForm.placeholder.load.balancer.key')
                      "
                    >
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item
                    :label="$t('load.balancer.expiry')"
                    field="loadbalancerExpiry"
                  >
                    <a-input-number
                      v-model="formData.loadbalancerExpiry"
                      :hide-button="true"
                      :placeholder="
                        $t('detailForm.placeholder.load.balancer.expiry')
                      "
                    >
                    </a-input-number>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-space>
      <div class="actions">
        <a-space>
          <a-button type="primary" :loading="loading" @click="onSubmitClick">
            {{ $t('submit') }}
          </a-button>
        </a-space>
      </div>
    </a-form>
    <a-modal
      v-model:visible="visible"
      :title="
        $t(
          `${
            isCreate
              ? 'projectTable.operation.create.projetct'
              : 'projectTable.operation.update.projetct'
          }`
        )
      "
      :mask-closable="false"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <a-form :model="form">
        <a-form-item field="host" label="Host">
          <a-input v-model="form.host" />
        </a-form-item>
        <a-form-item field="port" :label="$t('route.port')">
          <a-input-number v-model="form.port" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, nextTick } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import useLoading from '@/hooks/loading';
  import {
    getRoute,
    RouteDetailModel,
    RouteHostPortModel,
    insertRoute,
    updateRoute,
  } from '@/api/route';
  import { Message } from '@arco-design/web-vue';
  import { useRouteStore } from '@/store';

  const { t } = useI18n();
  const routeStore = useRouteStore();
  const visible = ref(false);
  const isCreate = ref(true);

  const projectId = computed(() => routeStore.getProjectIdCache);
  const routeId = computed(() => routeStore.getRouteIdCache);
  const form = ref<RouteHostPortModel>({
    id: 0,
    host: '',
    port: 0,
    routeId: routeId.value,
  });

  const formData = ref<RouteDetailModel>({
    id: routeId.value,
    projectId: projectId.value,
    downstreamPathTemplate: '/{url}',
    upstreamPathTemplate: '/undefined/{url}',
    upstreamHttpMethod: ['Get', 'Post', 'Put', 'Patch', 'Delete', 'Option'],
    downstreamHttpMethod: undefined,
    downstreamHttpVersion: '1.1',
    requestIdKey: undefined,
    routeIsCaseSensitive: undefined,
    serviceName: undefined,
    serviceNamespace: undefined,
    downstreamScheme: 'http',
    cacheTtlseconds: undefined,
    cacheRegion: undefined,
    qosExceptionsallowedbeforebreaking: undefined,
    qosDurationofbreak: undefined,
    qosTimeoutvalue: undefined,
    loadbalancerType: undefined,
    loadbalancerKey: undefined,
    loadbalancerExpiry: undefined,
    ratelimitEnableratelimiting: undefined,
    ratelimitPeriod: undefined,
    ratelimitPeriodtimespan: undefined,
    ratelimitLimit: undefined,
    ratelimitWhitelist: [],
    authenticationAuthenticationproviderkey: undefined,
    authenticationAllowedscopes: [],
    httphandlerAllowautoredirect: undefined,
    httphandlerUsecookiecontainer: undefined,
    httphandlerUsetracing: undefined,
    httphandlerUseproxy: undefined,
    httphandlerMaxconnectionsperserver: undefined,
    upstreamHost: undefined,
    key: undefined,
    delegatingHandlers: [],
    priority: 0,
    timeout: undefined,
    dangerousAcceptAnyServerCertificateValidator: undefined,
    securityIpallowedlist: undefined,
    securityIpblockedlist: undefined,
    enabled: true,
    routeHostPorts: [],
    routeProperties: [],
    sort: 0,
  });
  const formRef = ref<FormInstance>();
  const handleCancel = () => {
    visible.value = false;
  };
  const handleOk = async () => {
    visible.value = false;
    if (isCreate.value) {
      formData.value.routeHostPorts.push(form.value);
    }
    const msg = t('detailForm.submitSuccess');
    Message.success({
      content: msg,
      duration: 5 * 1000,
    });
  };
  const handleDelete = (deleteRouteHostPortParam: RouteHostPortModel) => {
    formData.value.routeHostPorts = formData.value.routeHostPorts.filter(
      (obj) => obj !== deleteRouteHostPortParam
    );
  };
  const handleEdit = (
    useCreate: boolean,
    editRouteHostPortParams: RouteHostPortModel | undefined
  ) => {
    if (useCreate) {
      form.value = {
        id: 0,
        host: '',
        port: 0,
        routeId: routeId.value,
      };
    } else {
      form.value = editRouteHostPortParams as RouteHostPortModel;
    }
    visible.value = true;
    isCreate.value = useCreate;
  };
  const { loading, setLoading } = useLoading();
  const onSubmitClick = async () => {
    try {
      setLoading(true);
      if (formData.value.id > 0) {
        const { data } = await updateRoute(formData.value);
        formData.value.id = data;
        routeStore.toggleRouteId(data);
      } else {
        const { data } = await insertRoute(formData.value);
        formData.value.id = data;
        routeStore.toggleRouteId(data);
      }
      const msg = t('route.submitSuccess');
      Message.success({
        content: msg,
        duration: 5 * 1000,
      });
      setLoading(false);
    } finally {
      setLoading(false);
    }
  };
  const fetchData = async () => {
    try {
      if (routeId.value > 0) {
        const { data } = await getRoute(routeId.value);
        formData.value = data;
      }
    } catch (err) {
      // you can report use errorHandler or other
    }
  };
  fetchData();

  /** ************************
   * 授权作用域新增编辑
   *********************** */
  const inputScopeRef = ref();
  const showScopeInput = ref(false);
  const inputScopeVal = ref('');

  const handleEditScopeTag = () => {
    showScopeInput.value = true;

    nextTick(() => {
      if (inputScopeRef.value) {
        inputScopeRef.value.focus();
      }
    });
  };

  const handleAddScopeTag = () => {
    if (inputScopeVal.value) {
      formData.value.authenticationAllowedscopes.push(inputScopeVal.value);
      inputScopeVal.value = '';
    }
    showScopeInput.value = false;
  };

  const handleRemoveScopeTag = (key: string) => {
    formData.value.authenticationAllowedscopes =
      formData.value.authenticationAllowedscopes.filter((tag) => tag !== key);
  };

  /** ************************
   * 限流白名单新增编辑
   *********************** */
  const inputWhiteListRef = ref();
  const showWhiteListInput = ref(false);
  const inputWhiteListVal = ref('');

  const handleEditWhiteListTag = () => {
    showWhiteListInput.value = true;

    nextTick(() => {
      if (inputWhiteListRef.value) {
        inputWhiteListRef.value.focus();
      }
    });
  };

  const handleAddWhiteListTag = () => {
    if (inputWhiteListVal.value) {
      formData.value.ratelimitWhitelist.push(inputWhiteListVal.value);
      inputWhiteListVal.value = '';
    }
    showWhiteListInput.value = false;
  };

  const handleRemoveWhiteListTag = (key: string) => {
    formData.value.ratelimitWhitelist =
      formData.value.ratelimitWhitelist.filter((tag) => tag !== key);
  };

  /** ************************
   * 委托处理新增编辑
   *********************** */
  const inputDelegatingHandlersRef = ref();
  const showDelegatingHandlersInput = ref(false);
  const inputDelegatingHandlersVal = ref('');

  const handleEditDelegatingHandlersTag = () => {
    showDelegatingHandlersInput.value = true;

    nextTick(() => {
      if (inputDelegatingHandlersRef.value) {
        inputDelegatingHandlersRef.value.focus();
      }
    });
  };

  const handleAddDelegatingHandlersTag = () => {
    if (inputDelegatingHandlersVal.value) {
      formData.value.delegatingHandlers.push(inputDelegatingHandlersVal.value);
      inputDelegatingHandlersVal.value = '';
    }
    showDelegatingHandlersInput.value = false;
  };

  const handleRemoveDelegatingHandlersTag = (key: string) => {
    formData.value.delegatingHandlers =
      formData.value.delegatingHandlers.filter((tag) => tag !== key);
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 40px 20px;
    overflow: hidden;
  }

  .actions {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 60px;
    padding: 14px 20px 14px 0;
    background: var(--color-bg-2);
    text-align: right;
  }
</style>
